# -*- coding: utf-8 -*-
import requests
import json
import uuid
from urllib import parse

API_KEY = "nf77dOq9EXGlthBSsbabYjkw"
SECRET_KEY = "sw26CNs9wGmDWTcvUGMHpTvKULtbu9dA"

def get_audio_from_text(text,file_name):
    upload_task_url = "https://aip.baidubce.com/rpc/2.0/tts/v1/create?access_token=" + get_access_token()
    download_audio_url = "https://aip.baidubce.com/rpc/2.0/tts/v1/query?access_token=" + get_access_token()

    upload_task_payload = json.dumps({
        "text": text,
        "voice": 5003,
        "lang": "zh",
        "speed": 5,
    })
    upload_task_headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    upload_task_response = requests.request("POST", upload_task_url, headers=upload_task_headers, data=upload_task_payload)

    task_id = json.loads(upload_task_response.text).get("task_id")
    task_status = json.loads(upload_task_response.text).get("task_status")
    if task_status != "Created":
        print("终止")

    download_audio_payload = json.dumps({
        "task_ids": [
            task_id
        ]
    })
    download_audio_headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    download_audio_response = None
    while(True):
        download_audio_response = requests.request("POST", download_audio_url, headers=download_audio_headers, data=download_audio_payload)
        if download_audio_response is not None and download_audio_response.status_code == 200 and download_audio_response.text is not None:
            return_json = json.loads(download_audio_response.text)
            if return_json is not None and return_json.get("tasks_info") is not None and len(return_json.get("tasks_info")) >= 1:
                if return_json.get("tasks_info")[0] is not None and (return_json.get("tasks_info")[0]).get("task_status") == "Success":
                    break
    download_audio_url = json.loads(download_audio_response.text).get("tasks_info")[0].get("task_result").get("speech_url")
    with open('./%s' % file_name, 'wb+') as f:
        f.write(requests.get(download_audio_url).content)


def get_audio_from_short_text(text,file_name):
    url = "https://tsn.baidu.com/text2audio"

    payload = 'tex='+parse.quote(text)+'&tok=' + get_access_token() + '&cuid='+str(uuid.uuid4())+'&ctp=1&lan=zh&spd=5&pit=5&vol=5&per=3&aue=3'
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': '*/*'
    }

    download_audio_response = requests.request("POST", url, headers=headers,data=payload)
    if download_audio_response is not None and download_audio_response.status_code == 200 and download_audio_response.text is not None:
        with open('./%s' % file_name, 'wb+') as f:
            f.write(download_audio_response.content)


def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))


def get_task_result(task_id):
    url = "https://aip.baidubce.com/rpc/2.0/tts/v1/query?access_token=" + get_access_token()

    payload = json.dumps({
        "task_ids": [
            task_id
        ]
    })
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)